package com.jinkaimen.kqb.connection;

import android.os.SystemClock;
import android.text.TextUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class FileUploadAndDownload {
    public static final String UPLOAD_PATH = "dfs/blockupload?";

    /**
     * @param path      文件路径
     * @param type      文件类型，取值为：IMG、AUDIO、VEDIO
     * @param oid       如果为修改组织认证图片或者头像时，需要提供上次图片ID
     * @param sp        服务码可枚举，可扩展。1：二人会话富文本；2：群会话；3组织认证图片；4头像
     * @param mCallBack 回调对象 处理 上传结果
     */

    public void UploadFile(String path, String type, String oid, String sp, CallBack mCallBack) {
        int maxlength = 184520;
        File file = new File(path);
//        String id = MD5Util.getMD5(file);
        String id = file.toString();
        int filesize = (int) file.length();
        int start = 0;
        int end = 0;
        if (filesize <= maxlength) {
            end = filesize;
        } else {
            end = maxlength;
        }
        int times = filesize % maxlength == 0 ? filesize / maxlength : filesize / maxlength + 1;
        for (int i = 0; i < times; i++) {

            StringBuffer strUrl = new StringBuffer();
            String baseUrl = "";
            strUrl.append(baseUrl + UPLOAD_PATH);
            strUrl.append("id=" + id);
            strUrl.append("&filesize=" + filesize);
            strUrl.append("&type=" + type);
            if (!TextUtils.isEmpty(oid)) {
                strUrl.append("&oid=" + oid);
            }
//            // 富文本接收方ID，用户telNo。该值可以为空。
//            if (!StringUtils.isNullOrEmpty(tid)) {
//                strUrl.append("&tid=" + tid);
//            } else {
            strUrl.append("&tid=" + "1");
//            }
            strUrl.append("&sp=" + sp);
//            if (!StringUtils.isNullOrEmpty(st)) {
//                strUrl.append("&st=" + st);
//            }
//            if (!StringUtils.isNullOrEmpty(retag)) {
//                strUrl.append("&retag=" + retag);
//            }
            strUrl.append("&range=" + start + "-" + end);


            byte[] data = null;
            InputStream is = null;
            OutputStream os = null;
            ByteArrayOutputStream baos = null;
            HttpURLConnection conn = null;
            try {
                URL url = new URL(strUrl.toString());
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setConnectTimeout(1000 * 30);
                conn.setReadTimeout(1000 * 30);
                conn.setRequestProperty("Host", baseUrl);
//                conn.setRequestProperty("Client-Info", DeviceUtils.getClientInfo());
//                conn.setRequestProperty("Content-Type", "multipart/form-data");
//                conn.setRequestProperty("Access-Token", BaseApplication.getInstance().getAccessToken());
                os = conn.getOutputStream();
                byte[] sendData = getData(path, start);
                os.write(sendData);// 将post数据发出去
                int responseCode = conn.getResponseCode();
                if (responseCode == 200) {
                    if (end == filesize) {
                        if (i == times - 1) {
                            mCallBack.processData(id);
                        }
                    } else {
                        start = end;
                        if (end + maxlength < filesize) {
                            end = end + maxlength;
                        } else {
                            end = filesize;
                        }
                    }
                } else {
                    mCallBack.processError("");
                    break;
                }

            } catch (Exception e) {
                mCallBack.processError("");
                break;
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (os != null) {
                        os.close();
                    }
                    if (baos != null) {
                        baos.close();
                    }
                    conn = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    private byte[] getData(String url, int start) throws Exception {
        int maxLength = 184520;
        File f = new File(url);
        FileInputStream in = new FileInputStream(f);
        byte[] data = new byte[(int) f.length()];
        in.read(data);
        in.close();
        byte[] data1;
        if (start + maxLength > f.length()) {
            int l = (int) (f.length() - start);
            data1 = new byte[l];
        } else {
            data1 = new byte[maxLength];
        }
        System.arraycopy(data, start, data1, 0, data1.length);
        return data1;
    }


    //下载文件

    /**
     * @param type      文件类型
     * @param md5       文件md5值
     * @param mCallBack 回调对象 下载成功后 返回文件存放路径
     */
    public void loadFile(final String type, final String md5, final String savePath, final CallBack<String> mCallBack) throws Exception {
        Thread t = new Thread(new Runnable() {
            String baseUrl = "";

            @Override
            public void run() {

                File f1 = new File(savePath);
                f1.mkdir();
                File file = null;
                if (type.equals("img")) {
                    file = new File(savePath, md5 + ".png");
                    if (file != null && file.length() != 0) {
                        return;
                    }
                } else {
                    file = new File(savePath, md5 + ".amr");
                }

                try {
                    file.createNewFile();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                int bytesum = 0;
                int byteread = 0;
                URL url = null;
                try {
                    String url_ = baseUrl + "/dfs/blockdownload?id=" + md5;
                    url = new URL(url_);
                } catch (MalformedURLException e1) {
                }

                try {
                    if (url != null) {
                        URLConnection conn = url.openConnection();
                        conn.setRequestProperty("Accept", "*/*");
                        conn.setRequestProperty("x-cvtt-agent", "Android");
                        conn.setRequestProperty("Client-Info", "ANDR/2.1.8");
//                    conn.setRequestProperty("Access-Token", BaseApplication.getInstance().getAccessToken());
                        InputStream inStream = conn.getInputStream();
                        FileOutputStream fs = new FileOutputStream(file.getAbsolutePath());
                        byte[] buffer = new byte[1024];
                        while ((byteread = inStream.read(buffer)) != -1) {
                            bytesum += byteread;
                            fs.write(buffer, 0, byteread);
                        }
                        SystemClock.sleep(500);
                        mCallBack.processData(file.getAbsolutePath());
                    }
                } catch (Exception e) {
                    mCallBack.processError("");
                    System.out.println(e.getMessage());
                }
            }
        });
        t.start();
    }

//    public static void upload(){
//        rx.Observable.create(new rx.Observable.OnSubscribe<File>() {
//            @Override
//            public void call(Subscriber<? super File> subscriber) {
//
//            }
//        });
//    }
}
